package org.dromara.comm_lhz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.comm_lhz.entity.AsActivityEntity;
import org.dromara.comm_lhz.entity.AsActivityImgEntity;
import org.dromara.comm_lhz.entity.dto.AsActivityDto;
import org.dromara.comm_lhz.entity.dto.AsActivityImgDto;
import org.dromara.comm_lhz.mapper.AsActivityHMapper;
import org.dromara.comm_lhz.service.AsActivityImgHService;
import org.dromara.comm_lhz.service.AsActivityHService;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class AsActivityHServiceImpl extends ServiceImpl<AsActivityHMapper, AsActivityEntity> implements AsActivityHService {

    @Autowired
    private AsActivityImgHService asActivityImgHService;

    /**
     * 查询活动信息
     *
     * @param keyword
     * @param state
     * @param timePeriod
     * @return
     */
    @Override
    public Page<AsActivityDto> selActivityInfo(String keyword, Integer state, String timePeriod, Pageable pageable) {

        LambdaQueryWrapper<AsActivityEntity> queryWrapper = new LambdaQueryWrapper<>();

        // 关键字查询
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like(AsActivityEntity::getActivityName, keyword)
                .or()
                .like(AsActivityEntity::getActivityDescribe, keyword);
        }

        // 活动状态过滤
        if (state != null && state != 0) {
            queryWrapper.eq(AsActivityEntity::getState, state);
        }

        // 根据时间段过滤
        LocalDateTime now = LocalDateTime.now();
        if (StringUtils.isNotBlank(timePeriod)) {
            switch (timePeriod) {
                case "3天内":
                    queryWrapper.between(AsActivityEntity::getEventStartTime, now, now.plusDays(3));
                    break;
                case "本周内":
                    queryWrapper.between(AsActivityEntity::getEventStartTime, now, now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)));
                    break;
                case "本周末":
                    queryWrapper.between(AsActivityEntity::getEventStartTime, now.with(TemporalAdjusters.next(DayOfWeek.SATURDAY)), now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)));
                    break;
                case "本月":
                    queryWrapper.between(AsActivityEntity::getEventStartTime, now, now.with(TemporalAdjusters.lastDayOfMonth()));
                    break;
                case "下月":
                    queryWrapper.between(AsActivityEntity::getEventStartTime, now.plusMonths(1).with(TemporalAdjusters.firstDayOfMonth()), now.plusMonths(1).with(TemporalAdjusters.lastDayOfMonth()));
                    break;
                default:
                    break;
            }
        }

        // 按最新发布排序
        queryWrapper.orderByDesc(AsActivityEntity::getCreateTime);

        // 分页查询活动信息
        Page<AsActivityEntity> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
        Page<AsActivityEntity> activityPage = this.page(page, queryWrapper);

        // 将实体转换为DTO，并设置图片路径
        List<AsActivityDto> asActivityDtos = activityPage.getRecords().stream().map(asActivityEntity -> {
            AsActivityDto asActivityDto = BeanUtil.copyProperties(asActivityEntity, AsActivityDto.class);
            List<String> imagePaths = asActivityImgHService.list(new LambdaQueryWrapper<AsActivityImgEntity>()
                    .eq(AsActivityImgEntity::getActivityId, asActivityEntity.getId()))
                .stream()
                .map(AsActivityImgEntity::getUrl)
                .collect(Collectors.toList());
            asActivityDto.setImagePaths(imagePaths);
            return asActivityDto;
        }).collect(Collectors.toList());

        // 构建分页结果
        Page<AsActivityDto> resultPage = new Page<>(pageable.getPageNumber(), pageable.getPageSize(), activityPage.getTotal());
        resultPage.setRecords(asActivityDtos);

        return resultPage;
    }


    /**
     * 添加活动基本信息和图片
     *
     * @param asActivityDto
     * @return
     */
    @Transactional
    @Override
    public void addActivityInfo(AsActivityDto asActivityDto) {
        // 活动基本信息
        AsActivityEntity asActivityEntity = BeanUtil.copyProperties(asActivityDto, AsActivityEntity.class);
        // 保存活动基本信息
        this.save(asActivityEntity);
        Long id = asActivityEntity.getId();

        List<AsActivityImgDto> imagePaths = asActivityDto.getImagePath();
        List<AsActivityImgEntity> asActivityImgEntities = imagePaths.stream().map(imgDto -> {
            AsActivityImgEntity asActivityImgEntity = new AsActivityImgEntity();
            asActivityImgEntity.setActivityId(id);
            asActivityImgEntity.setUrl(imgDto.getUrl());
            return asActivityImgEntity;
        }).toList();

        asActivityImgHService.saveBatch(asActivityImgEntities);
    }

    @Transactional
    @Override
    public void updateActivityInfo(AsActivityDto asActivityDto) {
        // 从 DTO 中获取活动 ID
        Long activityId = asActivityDto.getId();

        // 检查活动是否存在
        AsActivityEntity existingActivity = this.getById(activityId);
        if (existingActivity == null) {
            throw new RuntimeException("Activity with ID " + activityId + " does not exist.");
        }

        // 更新活动基本信息
        AsActivityEntity updatedActivityEntity = BeanUtil.copyProperties(asActivityDto, AsActivityEntity.class);
        updatedActivityEntity.setId(activityId);  // 保持 ID 不变
        this.updateById(updatedActivityEntity);  // 更新活动基本信息

        // 处理图片路径，将 URL 字符串转换为 AsActivityImgEntity 列表
        List<AsActivityImgEntity> asActivityImgEntities = asActivityDto.getImagePath().stream()
            .map(imgDto -> {
                AsActivityImgEntity asActivityImgEntity = new AsActivityImgEntity();
                asActivityImgEntity.setActivityId(activityId);
                asActivityImgEntity.setUrl(imgDto.getUrl());  // 使用 imgDto 的 URL
                return asActivityImgEntity;
            })
            .collect(Collectors.toList());

        // 清理旧图片数据（根据业务需求）
        asActivityImgHService.removeById(activityId);

        // 保存新图片数据
        asActivityImgHService.saveBatch(asActivityImgEntities);
    }

}
